"""
直接认证测试脚本
创建时间：2025-09-21
作者：开发团队
目的：直接测试认证服务而不通过API
"""

import sys
import os

# 添加项目路径
sys.path.append(os.path.join(os.path.dirname(__file__), 'backend', 'src'))

# 设置环境变量
os.environ['ENVIRONMENT'] = 'development'

from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from backend.src.core.security import verify_password
from backend.src.core.config import get_config
from backend.src.services.auth_service import get_user_by_username

def direct_auth_test():
    """直接认证测试"""
    print("直接认证测试...")
    
    try:
        # 获取配置
        config = get_config()
        print(f"数据库URL: {config.DATABASE_URL}")
        
        # 创建数据库引擎
        engine = create_engine(config.DATABASE_URL, echo=False)
        
        # 创建会话
        SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)
        db = SessionLocal()
        
        # 获取用户
        username = "guard001"
        password = "123456"
        
        print(f"尝试认证用户: {username}")
        user = get_user_by_username(db, username)
        if user:
            print(f"找到用户: {user.username}")
            print(f"用户ID: {user.id}")
            print(f"用户角色: {user.role}")
            print(f"密码哈希: {user.password_hash}")
            
            # 验证密码
            is_valid = verify_password(password, str(user.password_hash))
            print(f"密码验证结果: {is_valid}")
            
            if is_valid:
                print("认证成功!")
                return True
            else:
                print("密码错误!")
                return False
        else:
            print("用户不存在!")
            return False
        
        db.close()
    except Exception as e:
        print(f"认证测试出错: {e}")
        import traceback
        traceback.print_exc()
        return False

if __name__ == "__main__":
    print("直接认证测试")
    print("=" * 50)
    
    success = direct_auth_test()
    
    if success:
        print("\n直接认证测试成功!")
    else:
        print("\n直接认证测试失败!")